package sporteam.web.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import sporteam.common.PMF;
import sporteam.web.client.AEuser;
import sporteam.web.client.Activity;

import com.google.gson.Gson;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;

@SuppressWarnings("serial")
public class GSONcom extends HttpServlet {
	private static final Logger MyLog = Logger.getLogger(GSONcom.class
			.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// setup variables
		boolean foundInDB = true;
		Gson gson = new Gson();
		AEuser ae_user = null;
		PersistenceManager pm = null ;
		String facebookID = null;
		// print to appengine log
		MyLog.warning("handling gson com");

		// define response type to json type
		resp.setContentType("application/json");


		// searh for user in appengine server
		try {
			// Receive facebook id from client
			 facebookID = req.getParameter("facebookid");

			// get PMF instance
			 pm = PMF.get().getPersistenceManager();
			
			 ae_user = (AEuser) pm.getObjectById(AEuser.class, facebookID);
		} 
		catch (Exception e) 	
		{
			MyLog.warning("User not found in the Datastore. Creating new user and updating friend_lists...");
			UserLoadingUtils.HandleUserRegistration(facebookID, "");
		}

		AEuser backUPuser = new AEuser(ae_user);
		
		ArrayList<Activity> acts_to_send = null;
		try {
			if (foundInDB) {
				acts_to_send = new ArrayList<Activity>();

				// filter activities
				for (Activity act : backUPuser.GetActivities()) {
					if (!act.isClosedActivity()) {
						acts_to_send.add(act);
					}
				}
			}

			if (acts_to_send != null)
				backUPuser.setActivity(acts_to_send);
			
		} catch (Exception e) {
			MyLog.warning("filter");
			MyLog.warning(e.toString());
		}

		// build json object to send to user
		JSONObject json = new JSONObject();
		try {
			json.put("db_status", "not_found");
			json.put("user", gson.toJson(backUPuser));
			json.put("tracks", gson.toJson(backUPuser.GetTracks()));
			json.put("activities", gson.toJson(backUPuser.GetActivities()));
			json.put("friends", gson.toJson(backUPuser.getSporteamFriends()));
		} catch (Exception e) {
			MyLog.warning(e.toString());
		}

		// write json to HTTP response
		resp.getWriter().write(json.toString());
		resp.getWriter().flush();
		pm.close();
	}

	private AEuser createNewUser(String facebookID) {
		FacebookClient facebookClient = new DefaultFacebookClient();
		com.restfb.types.User facebook_user = facebookClient.fetchObject(facebookID, User.class);

		AEuser u = new AEuser();

		// Set the new user attributes.
		String[] name = facebook_user.getName().split(" ");
		String first_name = name[0].trim();
		String last_name = name[1].trim();
		u.SetFacebookID(facebook_user.getId());
		u.SetFirstName(first_name);
		u.SetLastName(last_name);
		u.SetGender(facebook_user.getGender());
		u.SetEmail(facebook_user.getEmail());
		u.UpdateDate();
		u.SetAge(20);
		return u;
	}
	
	
	private void updateFriendList(AEuser u, String facebookID) {
		// establish connection with facebook-graph API with a specific
		// access_token
		FacebookClient facebookClient = new DefaultFacebookClient();

		com.restfb.types.User facebook_user = facebookClient.fetchObject(facebookID,
				com.restfb.types.User.class); // me - the facebook user logged
												// in ATM.
		Connection<com.restfb.types.User> myFriends = facebookClient
				.fetchConnection("me/friends", com.restfb.types.User.class);
		PersistenceManager pm = PMF.get().getPersistenceManager();

		// make default in activity to be false
		String InActivityStr = "not_in_act";
		
		for (com.restfb.types.User friend : myFriends.getData()) {
			try {
				AEuser ae_user = pm.getObjectById(AEuser.class, friend.getId());

				// add friend to my friends_list
				u.addSporteamFriend(friend.getId() + ";" + friend.getName()
						+ ";" + InActivityStr + ";");

				// add myself too each friend's friend_list as well
				ae_user.addSporteamFriend(facebook_user.getId() + ";"
						+ facebook_user.getName() + ";" + InActivityStr + ";");

				ae_user.UpdateDate();
				pm.makePersistent(ae_user);

				MyLog.warning("added sporteam friend: " + friend.getId() + "in act status: " + InActivityStr);
			} catch (Exception e) {
				MyLog.warning("error in update friends :" + e.toString());
			}
		}
		pm.close();
	}
	
	

}
